import React, { useState, useEffect } from 'react';
import { is_empty, loc, ErrView, obj_empty } from 'sui';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart, ScatterChart } from 'echarts/charts';
import { LegendComponent, ToolboxComponent, GridComponent, DataZoomComponent } from 'echarts/components';

echarts.use([LegendComponent, BarChart, ToolboxComponent, ScatterChart, GridComponent, DataZoomComponent, CanvasRenderer, LineChart]);

const Echart = ({ main, width }) => {
    const [option, setOption] = useState();

    useEffect(() => {
        if (obj_empty(main)) {
            return;
        }

        const data = [];
        const legend = [];

        const line = main.line;
        if (!is_empty(line)) {
            const name = main.name;
            const symbol = main.symbol;

            line.forEach((d, i) => {
                const tmp = {
                    type: 'line',
                    emphasis: {
                        disabled: true,
                    },
                    data: d,
                };

                if (symbol === "no") {
                    tmp["symbol"] = 'none';
                }

                if (!is_empty(name)) {
                    const t = name[i];
                    if (t) {
                        tmp["name"] = t;
                        legend.push(t);
                    }
                }

                data.push(tmp);
            });
        }

        if (main.bar) {
            data.push({
                type: 'bar',
                barWidth: 20,
                emphasis: {
                    disabled: true,
                },
                data: main.bar,
            });
        }

        const getLine = (k) => {
            const d = main[k];
            if (is_empty(d)) {
                return;
            }

            const v = d[d.length - 1][1];
            let label = `${k.toUpperCase()}: `;

            if (main.yper) {
                if (main.total) {
                    label += (v * 100 / main.total).toFixed(0) + "%";
                }
                else {
                    label += (v * 100).toFixed(0) + "%";
                }
            }
            else {
                label += v.toFixed(2);
            }

            data.push({
                type: 'line',
                symbol: 'none',
                lineStyle: {
                    type: "dashed",
                },
                emphasis: {
                    disabled: true,
                },
                endLabel: {
                    show: true,
                    color: 'inherit',
                    formatter: (d) => label,
                    distance: 10,
                },
                data: main[k],
            });
        };

        const getG = () => {
            const g = main["g"];
            if (is_empty(g)) {
                return;
            }

            data.push({
                type: 'scatter',
                symbolSize: 10,
                itemStyle: {
                    opacity: 1,
                    borderColor: 'blue',
                    color: 'blue',
                },
                emphasis: {
                    disabled: true,
                },
                data: g,
            });
        };

        const getScatter = (k) => {
            const adj = main["adj"];
            if (obj_empty(adj)) {
                return;
            }

            const d = adj[k];
            if (is_empty(d)) {
                return;
            }

            legend.push(k);

            const tmp = {
                pt_1: "#d50000",
                pt_3: "#d50000",
                pt_5: "#3e2723",
                pt_7: "#ffd600",
            };

            const itemStyle = {
                opacity: 1,
            };

            let cl = tmp[k];
            if (cl) {
                itemStyle["borderColor"] = cl;
                itemStyle["color"] = cl;
            }

            data.push({
                name: k,
                type: 'scatter',
                symbolSize: 10,
                emphasis: {
                    disabled: true,
                },
                itemStyle: itemStyle,
                data: d,
            });
        };

        getLine("cl");
        getLine("ucl");
        getLine("lcl");

        getG();

        getScatter("pt_1");
        getScatter("pt_3");
        getScatter("pt_5");
        getScatter("pt_7");

        const xAxis = {
            type: 'value',
            splitLine: {
                show: true,
            }
        };

        if (main.xrange) {
            xAxis["min"] = main.x_min;
            xAxis["max"] = main.x_max;
            xAxis["axisLabel"] = {
                formatter: (value) => value.toFixed(2)
            }
        }
        else {
            xAxis["axisLabel"] = {
                formatter: (value) => value + 1
            }
        }

        const yAxis ={
            type: 'value',
            min: main.min,
            max: main.max,
            splitLine: {
                show: true,
            }
        };

        if (main.hide_y) {
            yAxis["show"] = false;
        }

        if (main.yper) {
            yAxis["axisLabel"] = {
                formatter: (value) => {
                    if (main.total) {
                        return (parseFloat(value) * 100 / main.total).toFixed(0) + "%";
                    }

                    return (parseFloat(value) * 100).toFixed(0) + "%";
                }
            }
        }
        else {
            yAxis["axisLabel"] = {
                formatter: (value) => value.toFixed(2)
            }
        }

        const opt = {
            legend: {
                data: legend,
                formatter: (name) => {
                    const tmp = {
                        pt_1: loc("zw_160"),
                        pt_3: loc("product_21"),
                        pt_5: loc("product_22"),
                        pt_7: loc("product_23"),
                    };

                    const v = tmp[name];
                    if (v) {
                        return v;
                    }

                    return name;
                }
            },
            toolbox: {
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none',
                        title: {
                            zoom: loc("zw_235"),
                            back: loc("zw_236"),
                        }
                    },
                    restore: {
                        title: loc("zw_237"),
                    },
                    saveAsImage: {
                        show: false,
                    }
                }
            },
            xAxis: xAxis,
            yAxis: yAxis,
            dataZoom: [
                {
                    type: 'slider',
                    height: 20,
                    start: 0,
                    end: 100
                },
            ],
            series: data,
        };

        setOption(opt);
    }, [main]);

    if (obj_empty(main)) {
        return null;
    }

    if (main.err) {
        return <ErrView err={main.err}/>;
    }

    if (obj_empty(option)) {
        return null;
    }

    return (
        <ReactEChartsCore echarts={echarts} option={option} style={{ height: '400px', width: width + "px" }}/>
    );
};


export {Echart};
